package com.trade.module.base.controller;

import com.trade.module.base.entity.SystemLog;
import com.trade.module.base.entity.User;
import com.trade.module.base.service.SystemLogService;
import com.trade.module.base.service.UserService;
import com.trade.common.utils.*;
import com.trade.common.utils.crypto.MD5Util;
import com.trade.module.base.vo.UserVo;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Class Description: 用户操作控制类
 *
 * @Version v1.0 2017/4/22 22:15
 * @JDK version 1.8.0_51
 * @Author zfb
 */
@Log4j
@Controller
@RequestMapping(value = "/base/user")
public class UserController extends BaseController {

    /**
     * Field description：注入日志服务层
     */
    @Autowired
    private SystemLogService systemLogService;

    /**
     * 注入用户服务层
     */
    @Autowired
    private UserService userService;


    /**
     * 获取当前用户的用户名
     *
     * @return ResponseBean
     */
    @ResponseBody
    @RequestMapping(value = "/account", method = RequestMethod.GET)
    public ResponseBean getCurrentUserAccount() {
        UserVo currentUser = getCurrentUser();
        String account = currentUser != null ? currentUser.getAccount() : "";
        return new ResponseBean<Object>(ResponseUtil.SELECT_OK_200, "获取数据成功", account);
    }

    /**
     * 新增用户
     *
     * @param userVo  用戶vo
     * @param request servlet請求
     * @return ResponseBean
     */
    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseBean save(@RequestBody UserVo userVo, HttpServletRequest request) {
        //获取当前操作人信息
        UserVo currentUser = getCurrentUser();
        String currentUserId = (currentUser != null) ? currentUser.getId() : "";
        String account = (currentUser != null) ? currentUser.getAccount() : null;
        // 存储用户前设置用户审核信息为已通过
        userVo.setCreaterId(currentUserId);
        userVo.setModifyId(currentUserId);
        userVo.setAuditId(currentUserId);
        userVo.setAuditFlag(Constants.USER_AUDITFLAG_OK);
        userVo.setApplyTime(new Date());//申請時間
        userVo.setAuditTime(new Date());//審核時間
        //默认用户初始密码与帐号一致
        userVo.setPassWord(MD5Util.getMD5String(userVo.getAccount()));
        User user = userService.save(userVo);
        if (user != null) {
            SystemLog systemLog = LogUtil.buildeLogBean(User.class, LogUtil.LogLevel.info,
                    LogUtil.CRUDType.create, LogUtil.OperatRsult.success, currentUserId,
                    account, user.getId(), NetUtil.getIp(request), "添加用戶成功！");
            systemLogService.save(systemLog);
            log.info(LogUtil.getLogJsonFromBean(systemLog).toString());
            //设置返回信息
            return new ResponseBean(ResponseUtil.MODIFY_OK_201, "添加成功");
        } else {
            //打印日志
            SystemLog sysLog = LogUtil.buildeLogBean(User.class, LogUtil.LogLevel.error,
                    LogUtil.CRUDType.create, LogUtil.OperatRsult.failure, currentUserId,
                    account, "", NetUtil.getIp(request),
                    "添加用户失败，用户帐号" + userVo.getAccount() + "已存在");
            systemLogService.save(sysLog);
            log.error(LogUtil.getLogJsonFromBean(sysLog).toString());
            // 设置返回信息
            return new ResponseBean(ResponseUtil.VERIFY_ERROR_422, "用户帐号已存在");
        }
    }


    /**
     * 获取当前登录的用户的详细信息
     *
     * @return ResponseBean
     */
    @ResponseBody
    @RequestMapping(value = "/self", method = RequestMethod.GET)
    public ResponseBean<UserVo> getUserSelf(HttpServletRequest request) {
        //获取当前操作人信息
        UserVo currentUser = getCurrentUser();
        String currentUserId = (currentUser != null) ? currentUser.getId() : "";
        String account = (currentUser != null) ? currentUser.getAccount() : "";
        UserVo userSelf = userService.findById(currentUserId);
        //打印日志，设置返回值
        if (userSelf != null) {
            SystemLog systemLog = LogUtil.buildeLogBean(User.class, LogUtil.LogLevel.info,
                    LogUtil.CRUDType.read, LogUtil.OperatRsult.success, currentUserId,
                    account, userSelf.getId(), NetUtil.getIp(request), "查询当前用户成功！");
            systemLogService.save(systemLog);
            log.info(LogUtil.getLogJsonFromBean(systemLog).toString());
            //设置返回信息
            return new ResponseBean<>(ResponseUtil.SELECT_OK_200, "获取数据成功", userSelf);
        } else {
            //打印日志
            SystemLog sysLog = LogUtil.buildeLogBean(User.class, LogUtil.LogLevel.error,
                    LogUtil.CRUDType.read, LogUtil.OperatRsult.failure, currentUserId,
                    account, "", NetUtil.getIp(request), "用户不存在");
            systemLogService.save(sysLog);
            log.error(LogUtil.getLogJsonFromBean(sysLog).toString());
            // 设置返回信息
            return new ResponseBean<>(ResponseUtil.NOT_EXIST_ERROR_404, "用户不存在");
        }
    }


    /**
     * Method description：修改当前登录用户的信息
     *
     * @param user 用户对象
     * @return ResponseBean
     */
    @ResponseBody
    @RequestMapping(value = "/info", method = RequestMethod.PUT)
    public ResponseBean updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        UserVo currentUser = getCurrentUser();
        String currentUserId = (currentUser != null) ? currentUser.getId() : "";
        user.setModifyId(currentUserId);
        User userPo = userService.saveInfo(user);
        if (userPo != null) {
            //syncService.syncAuthentication();
            //打印日志
            SystemLog sysLog = LogUtil.buildeLogBean(User.class, LogUtil.LogLevel.info, LogUtil.CRUDType.update, LogUtil.OperatRsult.success
                    , currentUserId, (currentUser != null) ? currentUser.getAccount() : "", user.getId(), NetUtil.getIp(request), "保存修改用户成功");
            systemLogService.save(sysLog);
            log.info(LogUtil.getLogJsonFromBean(sysLog).toString());
            // 设置返回信息
            return new ResponseBean(ResponseUtil.MODIFY_OK_201);
        } else {
            //打印日志
            SystemLog sysLog = LogUtil.buildeLogBean(User.class, LogUtil.LogLevel.error, LogUtil.CRUDType.update, LogUtil.OperatRsult.failure
                    , currentUserId, (currentUser != null) ? currentUser.getAccount() : "", "", NetUtil.getIp(request), "修改用户失败");
            systemLogService.save(sysLog);
            log.error(LogUtil.getLogJsonFromBean(sysLog).toString());
            // 设置返回信息
            return new ResponseBean(ResponseUtil.VERIFY_ERROR_422);
        }
    }


    /**
     * Method description：根据用户id修改用户密码
     *
     * @param userVo  用户vo
     * @param request 请求
     * @return ResponseBean
     */
    @ResponseBody
    @RequestMapping(value = "/passWord", method = RequestMethod.PUT)
    public ResponseBean updatePassWord(@RequestBody UserVo userVo, HttpServletRequest request) {
        UserVo currentUser = getCurrentUser();
        String currentUserId = (currentUser != null) ? currentUser.getId() : "";
        userVo.setId(currentUserId);
        userVo.setModifyId(currentUserId);
        boolean result = userService.updatePassWord(userVo);
        if (result) {
            //syncService.syncAuthentication();
            SystemLog sysLog = LogUtil.buildeLogBean(User.class, LogUtil.LogLevel.info, LogUtil.CRUDType.update, LogUtil.OperatRsult.success
                    , currentUserId, (currentUser != null) ? currentUser.getAccount() : "", currentUserId, NetUtil.getIp(request), "修改用户密码成功");
            systemLogService.save(sysLog);
            log.info(LogUtil.getLogJsonFromBean(sysLog).toString());
            return new ResponseBean(ResponseUtil.MODIFY_OK_201);
        } else {
            SystemLog sysLog = LogUtil.buildeLogBean(User.class, LogUtil.LogLevel.error, LogUtil.CRUDType.update, LogUtil.OperatRsult.success
                    , currentUserId, (currentUser != null) ? currentUser.getAccount() : "", currentUserId, NetUtil.getIp(request), "修改密码失败");
            systemLogService.save(sysLog);
            log.error(LogUtil.getLogJsonFromBean(sysLog).toString());
            return new ResponseBean(ResponseUtil.VERIFY_ERROR_422);
        }
    }
}
